package Init

import (
	"time"

	"gorm.io/gorm"
)

const (
	callBackBeforeName = "core:before"
	callBackAfterName  = "core:after"
	startTime          = "_start_time"
)

type TracePlugin struct{}

var _ gorm.Plugin = &TracePlugin{}

func (op *TracePlugin) Name() string {
	return "tracePlugin"
}

func (op *TracePlugin) Initialize(db *gorm.DB) (err error) {
	// 开始前
	// db.callbacks.processors["xxx"].Before() 返回一个 callback 结构体，
	// 并初始赋值：callback{before: name, processor: xxx的processor}，
	// callback.Register() 继续赋值：callback{name: callBackBeforeName, handler: before}，
	// 最后把构造的 callback 加到 db.callbacks.processor["xxx"].callbacks 列表中，
	_ = db.Callback().Create().Before("gorm:before_create").Register(callBackBeforeName, before)
	_ = db.Callback().Query().Before("gorm:query").Register(callBackBeforeName, before)
	_ = db.Callback().Delete().Before("gorm:before_delete").Register(callBackBeforeName, before)
	_ = db.Callback().Update().Before("gorm:setup_reflect_value").Register(callBackBeforeName, before)
	_ = db.Callback().Row().Before("gorm:row").Register(callBackBeforeName, before)
	_ = db.Callback().Raw().Before("gorm:raw").Register(callBackBeforeName, before)

	// 结束后
	_ = db.Callback().Create().After("gorm:after_create").Register(callBackAfterName, after)
	_ = db.Callback().Query().After("gorm:after_query").Register(callBackAfterName, after)
	_ = db.Callback().Delete().After("gorm:after_delete").Register(callBackAfterName, after)
	_ = db.Callback().Update().After("gorm:after_update").Register(callBackAfterName, after)
	_ = db.Callback().Row().After("gorm:row").Register(callBackAfterName, after)
	_ = db.Callback().Raw().After("gorm:raw").Register(callBackAfterName, after)
	return
}

func before(db *gorm.DB) {
	db.InstanceSet(startTime, time.Now())
}

func after(db *gorm.DB) {
	if !GetBoolConf("base.log.file_writer.on") {
		return
	}

	_ts, isExist := db.InstanceGet(startTime)
	if !isExist {
		return
	}

	ts, ok := _ts.(time.Time)
	if !ok {
		return
	}
	sql := db.Dialector.Explain(db.Statement.SQL.String(), db.Statement.Vars...)
	duration := time.Since(ts)

	traceContext := db.Statement.Context.Value(TraceKey{}).(*TraceContext)

	if db.Error != nil {
		Log.TagInfo(traceContext, DLTagMySqlFailed, map[string]interface{}{
			"sql": sql,
			"msg": db.Error.Error(),
		})
	} else {
		Log.TagInfo(traceContext, DLTagMySqlSuccess, map[string]interface{}{
			"sql":          sql,
			"affected_row": db.RowsAffected,
			"proc_time":    duration,
		})
	}
}
